package com.saic.data.job;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;

/**
 * @DESC:获得锁
 * @author 谈晟
 *
 */
public class GetLock {
	private static Logger logger = Logger.getLogger(GetLock.class);

	public static boolean getLock(CuratorFramework _client, String _UUID,
			String _path, String _lockName) throws Exception {
		String inforStr = _UUID + "," + System.currentTimeMillis();
		_client.create().creatingParentsIfNeeded()
				.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
				.forPath(_path + "/" + _lockName, inforStr.getBytes());
		List<String> locks = _client.getChildren().forPath(_path);
		logger.debug(locks);
		long minIndex = Long.MAX_VALUE;
		String minUUID = "";
		for (String lock : locks) {
			long index = Long.parseLong(lock.substring(lock.length() - 10));
			String getUUID = new String(_client.getData().forPath(
					_path + "/" + lock)).split(",")[0];
			String fileName = lock.substring(0, 32);
			if (fileName.trim().toLowerCase()
					.equals(_lockName.trim().toLowerCase())) {
				if (index < minIndex) {
					minUUID = getUUID;
					minIndex = index;
				}
				logger.debug(minUUID + " this UUID " + _UUID + " minUUID: "
						+ minUUID + " index: " + index + " minIndex: "
						+ minIndex + "");
			}
		}
		return minUUID.equals(_UUID);
	}

	public static List<String> isEmptyLock(CuratorFramework _client,
			String _path) throws Exception {
		return _client.getChildren().forPath(_path);
	}
	
	public static void dropLock(CuratorFramework _client,
			String _path,String _lockName) throws Exception {
		    _client.delete().forPath(_path + "/" + _lockName);
	}
}
